package com.TripMate.system.controller;

import com.TripMate.system.annotation.AuthCheck;
import com.TripMate.system.common.BaseResponse;
import com.TripMate.system.common.DeleteRequest;
import com.TripMate.system.common.ErrorCode;
import com.TripMate.system.common.ResultUtils;
import com.TripMate.system.constant.UserConstant;
import com.TripMate.system.exception.BusinessException;
import com.TripMate.system.exception.ThrowUtils;
import com.TripMate.system.model.dto.favorites.FavoritesByPostAddRequest;
import com.TripMate.system.model.dto.favorites.FavoritesByTripAddRequest;
import com.TripMate.system.model.dto.favorites.FavoritesQueryRequest;
import com.TripMate.system.model.entity.Favorites;
import com.TripMate.system.model.entity.Post;
import com.TripMate.system.model.entity.Trips;
import com.TripMate.system.model.entity.User;
import com.TripMate.system.model.vo.FavoritesByPostVO;
import com.TripMate.system.model.vo.FavoritesByTripVO;
import com.TripMate.system.model.vo.LoginUserVO;
import com.TripMate.system.service.FavoritesService;
import com.TripMate.system.service.PostService;
import com.TripMate.system.service.TripsService;
import com.TripMate.system.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 用户收藏接口
 *
 * @author dongyanmian
 */
@RestController
@RequestMapping("/favorites")
@Slf4j
@Api(tags = "用户收藏接口")
public class FavoritesController {

    @Resource
    private UserService userService;

    @Resource
    private FavoritesService favoritesService;

    @Resource
    private TripsService tripsService;

    @Resource
    private PostService postService;

    // region 增删改查

    /**
     * 创建用户行程收藏
     *
     * @param favoritesAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add/trip")
    @ApiOperation(value = "创建用户行程收藏")
    public BaseResponse<Long> addTrip(@RequestBody FavoritesByTripAddRequest favoritesAddRequest, HttpServletRequest request) {
        if (favoritesAddRequest == null || favoritesAddRequest.getTripId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        Long userId = userService.getLoginUser(request).getId();

        // 检查行程是否存在
        Trips trip = tripsService.getById(favoritesAddRequest.getTripId());
        if (trip == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "行程不存在");
        }

        // 检查用户是否已经收藏了该行程
        QueryWrapper<Favorites> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", userId)
                .eq("tripId", favoritesAddRequest.getTripId())
                .eq("isDelete", 0);
        if (favoritesService.count(queryWrapper) > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "已经收藏了该行程");
        }

        // 创建收藏记录
        Favorites favorites = new Favorites();
        favorites.setTripId(favoritesAddRequest.getTripId());
        favorites.setUserId(userId);

        boolean saveResult = favoritesService.save(favorites);
        ThrowUtils.throwIf(!saveResult, ErrorCode.OPERATION_ERROR, "用户行程收藏失败");

        // 更新行程的收藏状态
        trip.setIsFavorite(1);
        boolean updateResult = tripsService.updateById(trip);
        ThrowUtils.throwIf(!updateResult, ErrorCode.OPERATION_ERROR, "更新行程收藏状态失败");

        return ResultUtils.success(favorites.getId());
    }


    /**
     * 创建用户文案收藏
     *
     * @param favoritesByPostAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add/post")
    @ApiOperation(value = "创建用户文案收藏")
    public BaseResponse<Long> addPost(@RequestBody FavoritesByPostAddRequest favoritesByPostAddRequest, HttpServletRequest request) {
        if (favoritesByPostAddRequest == null || favoritesByPostAddRequest.getPostId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        Long userId = userService.getLoginUser(request).getId();

        // 检查文案是否存在
        Post post = postService.getById(favoritesByPostAddRequest.getPostId());
        if (post == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文案不存在");
        }

        // 检查用户是否已经收藏了该文案
        QueryWrapper<Favorites> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", userId)
                .eq("postId", favoritesByPostAddRequest.getPostId())
                .eq("isDelete", 0);
        if (favoritesService.count(queryWrapper) > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "已经收藏了该文案");
        }

        // 创建收藏记录
        Favorites favorites = new Favorites();
        BeanUtils.copyProperties(favoritesByPostAddRequest, favorites);
        favorites.setUserId(userId);

        boolean saveResult = favoritesService.save(favorites);
        ThrowUtils.throwIf(!saveResult, ErrorCode.OPERATION_ERROR, "文案收藏失败");

        // 更新文案的收藏状态
        post.setIsFavorite(1);
        boolean updateResult = postService.updateById(post);
        ThrowUtils.throwIf(!updateResult, ErrorCode.OPERATION_ERROR, "更新文案收藏状态失败");

        return ResultUtils.success(favorites.getId());
    }



    /**
     * 删除用户收藏
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @ApiOperation("删除用户收藏")
    public BaseResponse<Boolean> deleteFavorite(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long id = userService.getLoginUser(request).getId();
        Favorites favorites = new Favorites();
        QueryWrapper<Favorites> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", deleteRequest.getId());
        favorites = favoritesService.getOne(queryWrapper);
        if (!id.equals(favorites.getUserId()) || !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限删除收藏记录");
        }
        Integer tripId1 = favorites.getTripId();
        if (tripId1 != null) {
            QueryWrapper<Trips> queryWrapper2 = new QueryWrapper<>();
            QueryWrapper<Trips> id1 = queryWrapper2.eq("id", tripId1);
            if (id1 == null) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "行程不存在");
            }
            Trips one = tripsService.getOne(queryWrapper2);
            if (one.getIsFavorite() == 1) {
                one.setIsFavorite(0);
                tripsService.updateById(one);
            }
        }
        Long postId = favorites.getPostId();
        if (postId != null) {
            QueryWrapper<Post> queryWrapper3 = new QueryWrapper<>();
            QueryWrapper<Post> id2 = queryWrapper3.eq("id", postId);
            if (id2 == null) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "文案不存在");
            }
            Post one2 = postService.getOne(queryWrapper3);
            if (one2.getIsFavorite() == 1) {
                one2.setIsFavorite(0);
                postService.updateById(one2);
            }
        }

        boolean result = favoritesService.removeById(deleteRequest.getId());
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "删除收藏失败");
        return ResultUtils.success(result);
    }

    /**
     * 分页获取全部用户收藏（仅管理员）
     *
     * @param favoritesQueryRequest
     * @return
     */
    @PostMapping("/list/all/post")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation("分页获取全部用户的文案收藏（仅管理员）")
    public BaseResponse<Page<FavoritesByPostVO>> listFavoriteByPostAll(@RequestBody FavoritesQueryRequest favoritesQueryRequest) {
        long current = favoritesQueryRequest.getCurrent() == 0 ? 1 : favoritesQueryRequest.getCurrent();
        long size = favoritesQueryRequest.getPageSize() == 0 ? 10 : favoritesQueryRequest.getPageSize();

        Page<FavoritesByPostVO> pageParam = new Page<>(current, size);
        Page<FavoritesByPostVO> favoritesVOPage = favoritesService.getQueryByPostAll(pageParam, favoritesQueryRequest);
        if (favoritesVOPage == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "查询全部用户的文案收藏失败");
        }

        return ResultUtils.success(favoritesVOPage);
    }

    /**
     * 分页获取全部用户收藏（仅管理员）
     *
     * @param favoritesQueryRequest
     * @return
     */
    @PostMapping("/list/all/trip")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation("分页获取全部用户的行程收藏（仅管理员）")
    public BaseResponse<Page<FavoritesByTripVO>> listFavoriteByTripAll(@RequestBody FavoritesQueryRequest favoritesQueryRequest) {
        long current = favoritesQueryRequest.getCurrent() == 0 ? 1 : favoritesQueryRequest.getCurrent();
        long size = favoritesQueryRequest.getPageSize() == 0 ? 10 : favoritesQueryRequest.getPageSize();

        Page<FavoritesByTripVO> pageParam = new Page<>(current, size);
        Page<FavoritesByTripVO> favoritesVOPage = favoritesService.getQueryByTripAll(pageParam, favoritesQueryRequest);
        if (favoritesVOPage == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "查询全部用户的行程收藏失败");
        }

        return ResultUtils.success(favoritesVOPage);
    }


    /**
     * 分页获取用户的行程收藏
     *
     * @param favoritesQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/all/my/trip")
    @ApiOperation("分页获取用户的行程收藏")
    public BaseResponse<Page<FavoritesByTripVO>> listFavoriteByTrip(@RequestBody FavoritesQueryRequest favoritesQueryRequest, HttpServletRequest request) {
        long current = favoritesQueryRequest.getCurrent() == 0 ? 1 : favoritesQueryRequest.getCurrent();
        long size = favoritesQueryRequest.getPageSize() == 0 ? 10 : favoritesQueryRequest.getPageSize();

        Long userId = userService.getLoginUser(request).getId();

        Page<FavoritesByTripVO> pageParam = new Page<>(current, size);
        Page<FavoritesByTripVO> favoritesVOPage = favoritesService.getQueryByTrip(pageParam, favoritesQueryRequest, userId);
        if (favoritesVOPage == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "查询用户的行程收藏失败");
        }

        return ResultUtils.success(favoritesVOPage);
    }

    /**
     * 分页获取用户的文案收藏
     *
     * @param favoritesQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/all/my/post")
    @ApiOperation("分页获取用户的文案收藏")
    public BaseResponse<Page<FavoritesByPostVO>> listFavoriteByPost(@RequestBody FavoritesQueryRequest favoritesQueryRequest, HttpServletRequest request) {
        long current = favoritesQueryRequest.getCurrent() == 0 ? 1 : favoritesQueryRequest.getCurrent();
        long size = favoritesQueryRequest.getPageSize() == 0 ? 10 : favoritesQueryRequest.getPageSize();

        Long userId = userService.getLoginUser(request).getId();
        Page<FavoritesByPostVO> pageParam = new Page<>(current, size);
        Page<FavoritesByPostVO> favoritesVOPage = favoritesService.getQueryByPost(pageParam, favoritesQueryRequest, userId);
        if (favoritesVOPage == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "查询用户的文案收藏失败");
        }

        return ResultUtils.success(favoritesVOPage);
    }

    // endregion
}
